package com.wxb.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wxb.apiclientsdk.model.User;
import com.wxb.apiclientsdk.model.YoudaoRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.wxb.apiclientsdk.utils.SignUtils.genSign;

/**
 * 调用第三方接口的客户端
 */
public class Client {

    private String accessKey;

    private String secretKey;


    private static final String GATEWAY_HOST = "http://localhost:8090";

    public Client(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }


    private Map<String,String > getHeaderMap(String body){
        Map<String,String > hashMap = new HashMap<>();
        hashMap.put("accessKey",accessKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign", genSign(body,secretKey));
        return hashMap;
    }

    public String commonInvokeAPI(String Path,String params ){
//        String json = JSONUtil.toJsonStr(youdaoRequest);
        HttpResponse response = HttpRequest.post(GATEWAY_HOST +Path )
                .addHeaders(getHeaderMap(params))
                .body(params)
                .execute();
        System.out.println(response.getStatus());
        return response.body();
    }



    public String getUserNameByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse response = HttpRequest.post(GATEWAY_HOST + "/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(response.getStatus());
        return response.body();
    }

    public String textTranslate(YoudaoRequest youdaoRequest){
        String json = JSONUtil.toJsonStr(youdaoRequest);
        HttpResponse response = HttpRequest.post(GATEWAY_HOST + "/api/youdao/")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(response.getStatus());
        return response.body();
    }


}
